package cn.hxz.service;

import cn.hxz.mapper.TeacherMapper;
import cn.hxz.pojo.Teacher;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

import static org.junit.Assert.*;

/**
 * 业务层的测试
 */
public class TeacherServiceTest {

    //读取mybatis-config.xml文件
    InputStream is = null;
    // 类似JDBC的connection 用来执行sql语句
    SqlSession sqlSession = null;
    //mapper
    TeacherMapper teacherMapper;

    /**
     * 每次执行各方法的先前执行处理
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        //1.读取resource下mybatis-config.xml文件
        is = Resources.getResourceAsStream("mybatis-config.xml");
        //2.初始化mybatis，使用SqlSessionFactoryBuilder创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.打开会话，执行相应sql语句
        sqlSession = sqlSessionFactory.openSession();
        teacherMapper = sqlSession.getMapper(TeacherMapper.class);
    }
    /**
     * 每次方法执行后关闭操作性
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        //关闭会话
        sqlSession.close();
        //关闭流
        is.close();
    }

    //查询所有
    @Test
    public void selectAll() {
        String name = "";
        int pageIndex = 1;
        int pageSize = 10;
        List<Teacher> list = teacherMapper.selectAll(name, pageIndex, pageSize);
        System.out.println(list);
        Assert.assertTrue(list != null);
    }

    //保存
    @Test
    public void insert() {
        Teacher teacher = new Teacher();
        teacher.setName("张三");
        teacher.setSex("男");
        teacher.setPhone("10086");
        teacher.setAge(30);
        teacherMapper.insert(teacher);
        //提交
        sqlSession.commit();
        //sout 快捷键回车打印 输出返回的id
        System.out.println("id=" + teacher.getId());
        Assert.assertTrue(teacher.getId() > 0);
    }

    //编辑
    @Test
    public void update() {
        Teacher teacher = new Teacher();
        teacher.setId(1);
        teacher.setName("李四");
        teacher.setSex("男");
        teacher.setPhone("10088");
        teacher.setAge(23);
        teacherMapper.update(teacher);
        sqlSession.commit();
    }

    //删除
    @Test
    public void delete() {
        int id = 1;
        teacherMapper.delete(id);
        sqlSession.commit();
    }

    //查询单条
    @Test
    public void selectOne() {
        int id = 2;
        Teacher teacher = teacherMapper.selectOne(id);
        System.out.println(teacher);
    }
}